package com.mc.moring.main

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Process
import android.util.Log
import android.widget.Toast
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader

class LogcatService : Service() {
    private var mServiceLooper: Looper? = null
    private var mServiceHandler: ServiceHandler? = null
    private var logTime = 0

    companion object {
        const val TAG = "LogcatService"
    }

    private inner class ServiceHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            Log.d(TAG, "handleMessage")
            try {
                Thread.sleep(5000)
            } catch (e: InterruptedException) {
                Thread.currentThread().interrupt()
            }
        }
    }

    override fun onCreate() {
        Log.d(TAG, "onCreate")
//        val thread = HandlerThread(
//            "ServiceStartArguments",
//            Process.THREAD_PRIORITY_BACKGROUND
//        )
//        thread.start()
//
//        mServiceLooper = thread.looper
//        mServiceHandler = ServiceHandler(mServiceLooper!!)
        logTime = 1
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand")

//        val msg: Message? = mServiceHandler?.obtainMessage()
//        msg?.arg1 = startId
//        msg?.let {
//            mServiceHandler?.sendMessage(msg)
//        }
        if (logTime == 1) {
            logTime = 0
            //开始记录日志
            Thread {
                while (true) {
                    log()
                }
            }.start()
        }

        return START_STICKY
    }

    override fun onBind(intent: Intent): IBinder? {
        Log.d(TAG, "onBind")
        return null
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy")
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show()
    }

    private fun log() {
        Log.e("LogcatService", "log start")
        val cmds = arrayOf("logcat", "-c")
        val shellCmd = "logcat -v time -s *:W " // adb logcat -v time *:W
        val process: java.lang.Process
        val runtime = Runtime.getRuntime()
        val reader: BufferedReader
        try {
            runtime.exec(cmds).waitFor()
            process = runtime.exec(shellCmd)
            reader = BufferedReader(InputStreamReader(process.inputStream))
            var line: String
            while (reader.readLine().also { line = it } != null) {
                if (line.contains(Process.myPid().toString())) {
                    writeTofile(line)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.e("LogcatService", "log finished")
    }

    private fun writeTofile(line: String) {
        val content = line + "\r\n"
        val fileOne = File(
            getExternalFilesDir(null), "logcat1.txt"
        )
        val fileTwo = File(
            getExternalFilesDir(null), "logcat2.txt"
        )
        //创建文件
        if (!fileOne.exists()) {
            try {
                fileOne.createNewFile()
                val fos: FileOutputStream
                fos = FileOutputStream(fileOne, true)
                fos.write(content.toByteArray())
                fos.flush()
                fos.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        if (!fileTwo.exists()) {
            try {
                fileTwo.createNewFile()
                val fos: FileOutputStream
                fos = FileOutputStream(fileTwo, true)
                fos.write(content.toByteArray())
                fos.flush()
                fos.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        //先判断文件存储对象（两个文件循环记录日志）
        val putValue = getSharedPreferences("loginData", MODE_PRIVATE)
        val logcatTarget = putValue.getInt("logcatTarget", 1)
        var logcatWrite = logcatTarget
        if (logcatTarget == 1) {
            //记录到文件1
            //如果文件1过大，更换文件2
            if (fileOne.isFile && fileOne.exists()) {
                try {
                    val inputStream = FileInputStream(fileOne)
                    val size = inputStream.available().toLong()
                    if (size > 1024 * 1024 * 5) {
                        //如果文件2过大，先删除文件2
                        if (fileTwo.isFile && fileTwo.exists()) {
                            try {
                                val inputStream2 = FileInputStream(fileTwo)
                                val size2 = inputStream2.available().toLong()
                                if (size2 > 1024 * 1024 * 5) {
                                    fileTwo.delete()
                                }
                                inputStream2.close()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                        //重新创建文件2
                        if (!fileTwo.exists()) {
                            try {
                                fileTwo.createNewFile()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                        //更换日志存储文件
                        val save = getSharedPreferences("logcatData", MODE_PRIVATE).edit()
                        save.putInt("logcatTarget", 2)
                        save.commit()
                        logcatWrite = 2
                    }
                    inputStream.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        } else if (logcatTarget == 2) {
            //记录到文件2
            //如果文件2过大，更换文件1
            if (fileTwo.isFile && fileTwo.exists()) {
                try {
                    val inputStream2 = FileInputStream(fileTwo)
                    val size = inputStream2.available().toLong()
                    if (size > 1024 * 1024 * 5) {
                        //如果文件1过大，先删除文件1
                        if (fileOne.isFile && fileOne.exists()) {
                            try {
                                val inputStream = FileInputStream(fileOne)
                                val size2 = inputStream.available().toLong()
                                if (size2 > 1024 * 1024 * 5) {
                                    fileOne.delete()
                                }
                                inputStream.close()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                        //重新创建文件1
                        if (!fileOne.exists()) {
                            try {
                                fileOne.createNewFile()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                        //更换日志存储文件
                        val save = getSharedPreferences("logcatData", MODE_PRIVATE).edit()
                        save.putInt("logcatTarget", 1)
                        save.commit()
                        logcatWrite = 1
                    }
                    inputStream2.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        if (logcatWrite == 1) {
            //录入日记
            val fos: FileOutputStream
            try {
                fos = FileOutputStream(fileOne, true)
                fos.write(content.toByteArray())
                fos.flush()
                fos.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else if (logcatWrite == 2) {
            //录入日记
            val fos: FileOutputStream
            try {
                fos = FileOutputStream(fileTwo, true)
                fos.write(content.toByteArray())
                fos.flush()
                fos.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}